<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="帖子标题" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入帖子标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="评论量" prop="commentCount">
              <el-input v-model="queryParams.commentCount" placeholder="请输入评论量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="是否精选" prop="choiceFlag">
              <el-select v-model="queryParams.choiceFlag" placeholder="请选择是否精选" clearable >
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="是否置顶" prop="pinnedFlag">
              <el-select v-model="queryParams.pinnedFlag" placeholder="请选择是否置顶" clearable >
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="是否发布" prop="releaseFlag">
              <el-select v-model="queryParams.releaseFlag" placeholder="请选择是否发布" clearable >
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="是否隐藏 " prop="showFlag">
              <el-select v-model="queryParams.showFlag" placeholder="请选择是否隐藏 " clearable >
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable >
                <el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="编辑时间" prop="editTime">
              <el-date-picker clearable
                              v-model="queryParams.editTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择编辑时间"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['posts:posts:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['posts:posts:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['posts:posts:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['posts:posts:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="postsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="对象存储主键" align="center" prop="postId" v-if="true" />-->
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="帖子标题" align="center" prop="title" />
        <el-table-column label="帖子内容" show-overflow-tooltip align="center" prop="content" />
        <el-table-column label="点赞" align="center" prop="likeCount" />
        <el-table-column label="浏览量" align="center" prop="viewCount" />
        <el-table-column label="收藏量" align="center" prop="collectCount" />
        <el-table-column label="评论量" align="center" prop="commentCount" />
        <el-table-column label="封面图片" align="center" prop="cover" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.cover" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="是否精选" align="center" prop="choiceFlag">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.choiceFlag"/>
          </template>
        </el-table-column>
        <el-table-column label="是否置顶" align="center" prop="pinnedFlag">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.pinnedFlag"/>
          </template>
        </el-table-column>
        <el-table-column label="是否发布" align="center" prop="releaseFlag">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.releaseFlag"/>
          </template>
        </el-table-column>
        <el-table-column label="是否隐藏 " align="center" prop="showFlag">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.showFlag"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_common_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="编辑时间" align="center" prop="editTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.editTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['posts:posts:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['posts:posts:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改帖子对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="postsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="分类ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入分类ID" />
        </el-form-item>
        <el-form-item label="帖子标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入帖子标题" />
        </el-form-item>
        <el-form-item label="帖子内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="点赞" prop="likeCount">
          <el-input v-model="form.likeCount" placeholder="请输入点赞" />
        </el-form-item>
        <el-form-item label="浏览量" prop="viewCount">
          <el-input v-model="form.viewCount" placeholder="请输入浏览量" />
        </el-form-item>
        <el-form-item label="收藏量" prop="collectCount">
          <el-input v-model="form.collectCount" placeholder="请输入收藏量" />
        </el-form-item>
        <el-form-item label="评论量" prop="commentCount">
          <el-input v-model="form.commentCount" placeholder="请输入评论量" />
        </el-form-item>
        <el-form-item label="封面图片OSSid" prop="cover">
          <image-upload v-model="form.cover"/>
        </el-form-item>
        <el-form-item label="是否精选" prop="choiceFlag">
          <el-select v-model="form.choiceFlag" placeholder="请选择是否精选">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否置顶" prop="pinnedFlag">
          <el-select v-model="form.pinnedFlag" placeholder="请选择是否置顶">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否发布" prop="releaseFlag">
          <el-select v-model="form.releaseFlag" placeholder="请选择是否发布">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否隐藏 " prop="showFlag">
          <el-select v-model="form.showFlag" placeholder="请选择是否隐藏 ">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_common_status"
              :key="dict.value"
              :value="dict.value"
            >{{dict.value === '0' ? '正常' : '禁用'}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="编辑时间" prop="editTime">
          <el-date-picker clearable
                          v-model="form.editTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择编辑时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Posts" lang="ts">
import { listPosts, getPosts, delPosts, addPosts, updatePosts } from '@/api/posts/posts';
import { PostsVO, PostsQuery, PostsForm } from '@/api/posts/posts/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_common_status, sys_yes_no } = toRefs<any>(proxy?.useDict('sys_common_status', 'sys_yes_no'));

const postsList = ref<PostsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const postsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PostsForm = {
  postId: undefined,
  userId: undefined,
  categoryId: undefined,
  title: undefined,
  content: undefined,
  likeCount: undefined,
  viewCount: undefined,
  collectCount: undefined,
  commentCount: undefined,
  cover: undefined,
  choiceFlag: undefined,
  pinnedFlag: undefined,
  releaseFlag: undefined,
  showFlag: undefined,
  status: undefined,
  editTime: undefined,
  remark: undefined
}
const data = reactive<PageData<PostsForm, PostsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    title: undefined,
    content: undefined,
    commentCount: undefined,
    choiceFlag: undefined,
    pinnedFlag: undefined,
    releaseFlag: undefined,
    showFlag: undefined,
    status: undefined,
    editTime: undefined,
    params: {
    }
  },
  rules: {
    postId: [
      { required: true, message: "对象存储主键不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "分类ID不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "帖子标题不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "帖子内容不能为空", trigger: "blur" }
    ],
    likeCount: [
      { required: true, message: "点赞不能为空", trigger: "blur" }
    ],
    viewCount: [
      { required: true, message: "浏览量不能为空", trigger: "blur" }
    ],
    collectCount: [
      { required: true, message: "收藏量不能为空", trigger: "blur" }
    ],
    commentCount: [
      { required: true, message: "评论量不能为空", trigger: "blur" }
    ],
    choiceFlag: [
      { required: true, message: "是否精选不能为空", trigger: "change" }
    ],
    pinnedFlag: [
      { required: true, message: "是否置顶不能为空", trigger: "change" }
    ],
    releaseFlag: [
      { required: true, message: "是否发布不能为空", trigger: "change" }
    ],
    showFlag: [
      { required: true, message: "是否隐藏 不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    editTime: [
      { required: true, message: "编辑时间不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询帖子列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPosts(queryParams.value);
  postsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  postsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: PostsVO[]) => {
  ids.value = selection.map(item => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加帖子";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PostsVO) => {
  reset();
  const _postId = row?.postId || ids.value[0]
  const res = await getPosts(_postId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改帖子";
}

/** 提交按钮 */
const submitForm = () => {
  postsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.postId) {
        await updatePosts(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addPosts(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: PostsVO) => {
  const _postIds = row?.postId || ids.value;
  await proxy?.$modal.confirm('是否确认删除帖子编号为"' + _postIds + '"的数据项？').finally(() => loading.value = false);
  await delPosts(_postIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('posts/posts/export', {
    ...queryParams.value
  }, `posts_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
